package com.example.demo.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.CommWxUrl;
import com.example.demo.vo.JsTokenVO;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Description:
 * @author: liyuan
 * @data 2020-11-23 09:56
 */
@RestController
@RequestMapping("/")
public class WxLoginController {
    @Value("${miniProgram.appId}")
    private String APPID;
    @Value("${miniProgram.appSecret}")
    private String SECRET;
    private Logger logger = LoggerFactory.getLogger(WxLoginController.class);
    @Autowired
    private RestTemplate restTemplate;

    /***
     *   获取opendi和unionid
     * @param code
     * @return
     */
    @RequestMapping("wxlogin")
    public ResultVO login(@RequestParam(value = "code") String code) {
        logger.info(code);//05347KFa1iiB1A0S9PGa1dugu5247KFv
        String result = restTemplate.getForObject(CommWxUrl.getWxLoginUrl(APPID, SECRET, code), String.class);
        return new ResultVO(1000, showLoginInfo(result));
    }

    /***
     *  提取用户信息
     * @param result
     * @return 失败时："data": {
    "errcode": 40029,
    "errmsg": "invalid code, hints: [ req_id: vflfqNnre-fpzKwa ]"
    }
     */
    private JsTokenVO showLoginInfo(String result) {
        logger.info(result);
        JsTokenVO jsTokenPO = JSONObject.parseObject(result, JsTokenVO.class);
        if (result != null && jsTokenPO.getOpenid() == null) {
            jsTokenPO.setErrcode(jsTokenPO.getErrcode());
            jsTokenPO.setErrmsg("识别出错");
            return jsTokenPO;
        }
        //只能得到openid，其他没有
        jsTokenPO.setSession_key(null);
        return jsTokenPO;
    }


}
